package com.sxy.web; /**
 * @author 宋鑫宇
 * @version 1.0
 */

import com.sxy.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收前端发送的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
        //获取随机生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        //比对验证码是否相同
        if (!(checkCodeGen.equalsIgnoreCase(checkCode))) {
            request.setAttribute("err_msg", "验证码输入错误");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        //调用service层执行方法
        boolean flag = userService.register(username, password);
        if (flag) {
            //注册成功
            request.setAttribute("register_msg", "注册成功，请登录.");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            //注册失败
            request.setAttribute("register_msg", "用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
